<?php

namespace app\admin\controller;


use app\common\controller\Backend;
use app\admin\model\Province;
use app\admin\model\City;
use app\admin\model\Area;
use app\admin\model\Admin;
use think\Db;
/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Project extends Backend
{
    
    /**
     * Project模型对象
     * @var \app\admin\model\Project
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Project;

        $Plist = Province::getList();
        
        $this->view->assign("Plist", $Plist);
    }
    
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
        // $Province = new Province();
        // $list = $Province->getList();

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams(['name','address']);
            
            $total = $this->model
                    ->with(['province','city','area','admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['province','city','area','admin'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $oid_arr = [];
            
            //总金额
            foreach ($list as $row) {
                $row['need_money'] = db('order')->where(['pid'=>$row['id'],'status'=>2])->sum('money');
                $oid_arr = db('order')->where(['pid'=>$row['id'],'status'=>2])->select();
                // $oids = array_column($oid_arr,'id');
                // $row['qian_money'] = db('qian')->where(['oid'=>['in',$oids]])->sum('account');
            }

            
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
    //获取省code返回列表
    public function getpro(){

        $province_code = $this->request->request('provice_id');
        $Clist = City::getList($province_code);
        //编辑时使用
        if($this->request->request("keyValue")){
            $keyValue = $this->request->request("keyValue");
            foreach($Clist as $k=>$v){
                if($v['Code'] == $keyValue){
                    $name = $v['Name'];
                }
            }
          return ['total'=>1, 'list'=>[
                ['Code'=>$keyValue, 'Name'=>$name]
            ]
          ];
        }

        return json(['list'=>$Clist,'total'=>count($Clist)]);
        
    }

    public function agent($pro){
        
        $arr = ['110000','120000','310000','500000'];
        // if(in_array($pro,$arr)){
            
        // }

        $data = db('shop')->where(['provice_id'=>$pro,'switch'=>1,'tag'=>['neq','normal']])->select();
        if($data){
            $this->Res['code'] = 1;
            $this->Res['info'] = $data;
            return $this->Res;
        }else{
            $this->Res['info'] = '该地区暂无代理';
            return $this->Res;
        }
    }

     //获取市code返回列表
    public function getcity(){
        $city_id_code = $this->request->request('city_id');
        $Clist = Area::getList($city_id_code);
        // dump($this->request->request("keyValue"));
        // die;
        //编辑时使用
        if($this->request->request("keyValue")){

            $keyValue = $this->request->request("keyValue");
            foreach($Clist as $k=>$v){
                if($v['Code'] == $keyValue){
                    $name = $v['Name'];
                }
            }
          return ['total'=>1, 'list'=>[
                ['Code'=>$keyValue, 'Name'=>$name]
            ]
          ];
        }
        return json(['list'=>$Clist,'total'=>count($Clist)]);
        
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['addtime'] = date('Y-m-d H:i:s');
                    if(!empty($params['img'])){
                        $arr = [];
                        for ($i=0; $i < 100 ; $i++) { 
                            if(isset($params['img'.$i])){
                                // $arr['img'.$i] = $params['img'.$i];
                                $arr[$i]['title'] = 'img'.$i;
                                $arr[$i]['imgurl'] = $params['img'.$i];
                                unset($params['img'.$i]);
                            }else{
                                break;
                            }
                            
                        }
                        
                    }
                    
                    $result = $this->model->allowField(true)->insertGetId($params);

                    if(!empty($arr)){
                        foreach($arr as $k=>$v){
                            $arr[$k]['pid'] = $result;
                        }
                        db('projectimg')->insertAll($arr);
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            
            //项目负责人
            $admin_list = Admin::getList();
            $this->assign('admin_list',$admin_list);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        //门店归属
        // $pidlist = db('shop')->where(['switch'=>1,'provice_id'=>$row->provice_id,'tag'=>['neq','normal']])->select();
        
        // foreach($pidlist as $k=>$v){
        //     $arr[$v['id']] = $v['shop_name'];
        // }
        
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //项目负责人
        $imgs = db('projectimg')->where(['pid'=>$ids,'switch'=>1])->select();
        if(!empty($imgs)){
            // foreach($imgs as $k=>$v){
            //     $imgstr = $v['title'];
            //     $this->model->$imgstr = $v['imgurl'];
            //     unset($imgstr);
            // }
            // dump($this->model->img0);
            // dump($row);
            // die;
            $this->assign('imgs',$imgs);
        }
        
        $admin_list = Admin::getList();
        $this->assign('admin_list',$admin_list);
        $this->view->assign("row", $row);
        //$this->view->assign("pidlist", $arr);
        return $this->view->fetch();
    }

}
